package com.wayz.serivce;

import com.wayz.annotation.DYGTransactional;
import com.wayz.constants.CLiveTempletAdslotType;
import com.wayz.constants.PageVo;
import com.wayz.constants.ViewMap;
import com.wayz.entity.dto.live.LiveTempletAdslotDto;
import com.wayz.entity.dto.live.LiveTempletDto;
import com.wayz.entity.dto.live.LiveTempletPageDto;
import com.wayz.entity.pojo.live.*;
import com.wayz.entity.redis.user.RUser;
import com.wayz.entity.vo.live.LiveResolutionVo;
import com.wayz.entity.vo.live.LiveTempletAdslotVo;
import com.wayz.entity.vo.live.LiveTempletDetailVo;
import com.wayz.entity.vo.live.LiveTempletVo;
import com.wayz.exception.WayzException;
import com.wayz.mapper.DCompanyMaterialDAO;
import com.wayz.mapper.DLiveChannelDAO;
import com.wayz.mapper.DLiveTempletAdslotDAO;
import com.wayz.mapper.DLiveTempletDAO;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RUserObject;
import com.wayz.redis.RedisUtils;
import com.wayz.service.LiveService;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 直播服务实现类
 * 
 */
@Service("liveService")
@org.apache.dubbo.config.annotation.Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class LiveServiceImpl implements LiveService {

    /** Redis工具类 */
    @Resource(name = "redisUtils")
    private RedisUtils redisUtils;

    /** DAO相关 */
    /** 直播渠道DAO */
    @Resource(name = "dLiveChannelDAO")
    private DLiveChannelDAO dLiveChannelDAO = null;

    /** 用户对象 */
    @Resource(name = "rUserObject")
    private RUserObject rUserObject = null;

    /** 直播模板DAO */
    @Resource(name = "dLiveTempletDAO")
    private DLiveTempletDAO dLiveTempletDAO = null;
    /** 直播模板分屏配置DAO */
    @Resource(name = "dLiveTempletAdslotDAO")
    private DLiveTempletAdslotDAO dLiveTempletAdslotDAO = null;
    /** 广告素材DAO */
    @Resource(name = "dCompanyMaterialDAO")
    private DCompanyMaterialDAO dCompanyMaterialDAO = null;


    @Override
    public Long createLiveChannel(Long myId, String name) throws WayzException {
        if (dLiveChannelDAO.existsName(name, null)) {
            throw new WayzException("直播渠道名称已存在!");
        }
        Long id = redisUtils.incrBy(BeanIdKeyEnum.LIVE_CHANNEL.getKey(), RedisUtils.STEP_SIZE);
        dLiveChannelDAO.create(id, name);
        return null;
    }

    @Override
    public void modifyLiveChannel(Long myId, Long id, String name) throws WayzException {
        if (dLiveChannelDAO.existsName(name, id)) {
            throw new WayzException("直播渠道名称已存在!");
        }
        dLiveChannelDAO.modify(id, name);
    }

    @Override
    public void deleteLiveChannel(Long myId, Long id) throws WayzException {
        DLiveChannel vo = dLiveChannelDAO.get(id);
        if (vo == null) {
            throw new WayzException("直播渠道不存在!");
        }
        dLiveChannelDAO.delete(id);
    }

    @Override
    public List<DLiveChannel> queryLiveChannel(Long myId) throws WayzException {
        List<DLiveChannel> list = dLiveChannelDAO.query();
        return list;
    }

    /**
     * 查询分辨率
     *
     * @param myId 我的客户标识
     * @return 分辨率列表
     * @throws WayzException 平台异常
     */
    @Override
    public List<ViewMap> queryLiveResolutionView(Long myId) throws WayzException {
        // 查询分辨率视图信息
        List<ViewMap> resolutionList = dLiveTempletDAO.queryLiveResolutionView();

        // 返回数据
        return resolutionList;
    }

    /**
     * 获取分辨率
     *
     * @param myId 我的标识
     * @param id 分辨率标识
     * @return 分辨率
     * @throws WayzException 平台异常
     */
    @Override
    public LiveResolutionVo getLiveResolution(Long myId, Long id) throws WayzException {
        DLiveResolution dLiveResolution = dLiveTempletDAO.getLiveResolution(id);
        LiveResolutionVo liveResolutionVo = new LiveResolutionVo();
        BeanUtils.copyProperties(dLiveResolution, liveResolutionVo);
        return liveResolutionVo;
    }

    @Override
    public PageVo<LiveTempletVo> queryLivePlanTemplet(Long myId, LiveTempletPageDto liveTempletPageDto) {

        Long companyId = liveTempletPageDto.getCompanyId();
        String name = liveTempletPageDto.getName();
        Long resolutionId = liveTempletPageDto.getResolutionId();

        // 获取公司
        if (companyId == null) {
            RUser rUser = rUserObject.get(myId);
            companyId = rUser.getCompanyId();
        }
        // 初始化
        PageVo<LiveTempletVo> page = new PageVo<>();
        Integer totalCount = dLiveTempletDAO.count(companyId, name, resolutionId);
        if (totalCount <= 0) {
            return page;
        }
        List<LiveTempletVo> templetList = new ArrayList<LiveTempletVo>();
        List<DLiveTemplet> list = dLiveTempletDAO.query(companyId, name, resolutionId, liveTempletPageDto.getStartIndex(), liveTempletPageDto.getPageSize());
        if (list != null && list.size() > 0) {
            for (DLiveTemplet vo : list) {
                LiveTempletVo playTemplet = new LiveTempletVo();
                playTemplet.setId(vo.getId());
                playTemplet.setName(vo.getName());
                playTemplet.setPreviewUrl(vo.getPreviewUrl());
                playTemplet.setResolutionId(vo.getResolutionId());
                playTemplet.setResolutionName(vo.getResolutionName());
                //playTemplet.setCreatedTime(TimeHelper.getTimestamp(vo.getCreatedTime()));
               // playTemplet.setModifiedTime(vo.getModifiedTime());
                playTemplet.setDescription(vo.getDescription());

                templetList.add(playTemplet);
            }
        }
        page.setList(templetList);
        page.setTotalCount(totalCount);
        return page;
    }

    @Override
    public List<ViewMap> queryLivePlanTempletView(Long myId, Long companyId) throws WayzException {
        // 获取公司
        if (companyId == null) {
            RUser rUser = rUserObject.get(myId);
            companyId = rUser.getCompanyId();
        }
        // 初始化
        List<ViewMap> viewList = dLiveTempletDAO.queryLiveTempletView(companyId);

        // 返回数据
        return viewList;
    }

    @Override
    @DYGTransactional
    public void createLivePlanTemplet(Long myId, LiveTempletDto liveTempletDto) throws WayzException {

        Long companyId = liveTempletDto.getCompanyId();
        String name = liveTempletDto.getName();
        Long resolutionId = liveTempletDto.getResolutionId();
        List<LiveTempletAdslotDto> adslotList = liveTempletDto.getAdslotList();

        // 获取公司
        if (companyId == null) {
            RUser rUser = rUserObject.get(myId);
            companyId = rUser.getCompanyId();
        }
        // 校验名称唯一
        if (dLiveTempletDAO.queryUnique(companyId, name, null)) {
            throw new WayzException(MessageFormat.format("直播模板名称已存在:{0}", name));
        }
        // 处理直播模板信息
        Long id = redisUtils.incrBy(BeanIdKeyEnum.LIVE_TEMPLET.getKey(), RedisUtils.STEP_SIZE);
        DLiveTemplet create = new DLiveTemplet();
        create.setId(id);
        create.setName(name);
        create.setCompanyId(companyId);
        create.setPreviewUrl(liveTempletDto.getPreviewUrl());
        create.setBackground(liveTempletDto.getBackground());
        create.setBackgroundAudio(liveTempletDto.getBackgroundAudio());
        create.setResolutionId(resolutionId);
        dLiveTempletDAO.create(create);

        // 添加分屏信息
        if (adslotList != null && adslotList.size() > 0) {
            createLiveTempletAdslot(adslotList, id, resolutionId);
        }
    }

    /**
     * 创建直播模板分屏配置
     *
     * @param adslotList
     * @throws WayzException
     */
    public void createLiveTempletAdslot(List<LiveTempletAdslotDto> adslotList, Long id, Long resolutionId)
            throws WayzException {
        for (LiveTempletAdslotDto templetAdslot : adslotList) {
            DLiveTempletAdslot create = new DLiveTempletAdslot();
            create.setTempletId(id);
            create.setName(templetAdslot.getName());
            create.setUrl(templetAdslot.getUrl());
            create.setType(templetAdslot.getType());
            create.setJsonTxt(templetAdslot.getJsonTxt());
            create.setTop(templetAdslot.getTop());
            create.setLft(templetAdslot.getLft());
            create.setHeight(templetAdslot.getHeight());
            create.setWidth(templetAdslot.getWidth());
            create.setNum(templetAdslot.getNum());
            create.setMaterialId(templetAdslot.getMaterialId());
            if (templetAdslot.getType() == CLiveTempletAdslotType.IMAGE_FIXED.getValue()) {
                DCompanyMaterial dCompanyMaterial = dCompanyMaterialDAO.get(templetAdslot.getMaterialId());
                create.setUrl(dCompanyMaterial.getUrl());
                create.setJsonTxt(dCompanyMaterial.getFilemd5());
            }
            dLiveTempletAdslotDAO.create(create);
        }
    }

    @Override
    @DYGTransactional
    public void modifyLivePlanTemplet(Long myId, LiveTempletDto liveTempletDto)
            throws WayzException {

        Long id = liveTempletDto.getId();
        Long companyId = liveTempletDto.getCompanyId();
        String name = liveTempletDto.getName();
        Long resolutionId = liveTempletDto.getResolutionId();
        List<LiveTempletAdslotDto> adslotList = liveTempletDto.getAdslotList();

        // 获取公司
        if (companyId == null) {
            RUser rUser = rUserObject.get(myId);
            companyId = rUser.getCompanyId();
        }
        // 验证直播模板是否存在
        DLiveTemplet dPlayTemplet = dLiveTempletDAO.get(id);
        if (dPlayTemplet == null) {
            throw new WayzException(MessageFormat.format("直播模板不存在:{0}", id));
        }
        // 校验名称唯一
        if (dLiveTempletDAO.queryUnique(companyId, name, id)) {
            throw new WayzException(MessageFormat.format("直播模板名称已存在:{0}", name));
        }
        // 修改基础信息
        DLiveTemplet modify = new DLiveTemplet();
        modify.setId(id);
        modify.setName(name);
        modify.setPreviewUrl(liveTempletDto.getPreviewUrl());
        modify.setBackground(liveTempletDto.getBackground());
        modify.setResolutionId(resolutionId);
        modify.setBackgroundAudio(liveTempletDto.getBackgroundAudio());
        dLiveTempletDAO.modify(modify);

        // 删除已有的分屏信息
        dLiveTempletAdslotDAO.delete(id);

        // 添加分屏信息
        if (adslotList != null && adslotList.size() > 0) {
            createLiveTempletAdslot(adslotList, id, resolutionId);
        }
    }

    @Override
    public void deleteLivePlanTemplet(Long myId, Long id) throws WayzException {
        // 验证直播模板是否存在
        DLiveTemplet dPlayTemplet = dLiveTempletDAO.get(id);
        if (dPlayTemplet == null) {
            throw new WayzException(MessageFormat.format("直播模板不存在:{0}", id));
        }

        // 删除
        DLiveTemplet modify = new DLiveTemplet();
        modify.setId(id);
        modify.setIsDeleted(true);
        dLiveTempletDAO.modify(modify);
    }

    @Override
    public LiveTempletDetailVo getLivePlanTempletDetail(Long myId, Long templetId) throws WayzException {
        // 获取模板信息
        DLiveTemplet dLiveTemplet = dLiveTempletDAO.get(templetId);
        if (dLiveTemplet == null) {
            throw new WayzException(MessageFormat.format("直播模板不存在:{0}", templetId));
        }

        // 初始化
        LiveTempletDetailVo vo = new LiveTempletDetailVo();
        vo.setId(dLiveTemplet.getId());
        vo.setResolutionId(dLiveTemplet.getResolutionId());
        vo.setResolutionName(dLiveTemplet.getResolutionName());
        vo.setName(dLiveTemplet.getName());
        vo.setPreviewUrl(dLiveTemplet.getPreviewUrl());
        vo.setDescription(dLiveTemplet.getDescription());
        vo.setBackground(dLiveTemplet.getBackground());
        //vo.setCreatedTime(TimeHelper.getTimestamp(dLiveTemplet.getCreatedTime());
        //vo.setModifiedTime(TimeHelper.getTimestamp(dLiveTemplet.getModifiedTime()));

        // 获取直播模板分屏配置
        List<LiveTempletAdslotVo> adslotList = queryLiveTempletAdslotList(templetId);
        if (adslotList != null && adslotList.size() > 0) {
            vo.setAdslotList(adslotList);
        }

        // 返回数据
        return vo;
    }

    /**
     * 查询直播模板分屏配置
     *
     * @param templetId
     */
    private List<LiveTempletAdslotVo> queryLiveTempletAdslotList(Long templetId) {
        // 初始化
        List<LiveTempletAdslotVo> adslotList = new ArrayList<LiveTempletAdslotVo>();

        // 查询直播模板分屏配置
        List<DLiveTempletAdslot> list = dLiveTempletAdslotDAO.query(templetId);
        if (list != null && list.size() > 0) {
            for (DLiveTempletAdslot vo : list) {
                LiveTempletAdslotVo liveTempletAdslotVo = new LiveTempletAdslotVo();
                liveTempletAdslotVo.setTempletId(vo.getTempletId());
                liveTempletAdslotVo.setNum(vo.getNum());
                liveTempletAdslotVo.setName(vo.getName());
                liveTempletAdslotVo.setUrl(vo.getUrl());
                liveTempletAdslotVo.setType(vo.getType());
                liveTempletAdslotVo.setJsonTxt(vo.getJsonTxt());
                liveTempletAdslotVo.setTop(vo.getTop());
                liveTempletAdslotVo.setLft(vo.getLft());
                liveTempletAdslotVo.setWidth(vo.getWidth());
                liveTempletAdslotVo.setMaterialId(vo.getMaterialId());
                liveTempletAdslotVo.setHeight(vo.getHeight());

                //liveTempletAdslotVo.setCreatedTime(TimeHelper.getTimestamp(vo.getCreatedTime()));
                //liveTempletAdslotVo.setModifiedTime(TimeHelper.getTimestamp(vo.getModifiedTime()));
                adslotList.add(liveTempletAdslotVo);
            }
        }
        return adslotList;
    }

}
